package com.itheima.springbootmybatis.controller;

import com.itheima.springbootmybatis.common.MessageConstant;
import com.itheima.springbootmybatis.common.Result;
import com.itheima.springbootmybatis.domain.User;
import com.itheima.springbootmybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/findAll")
    public Result findAll() {
        try {
            List<User> userList = userService.findAll();
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS, userList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }

    }
    //更新操作
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        try {
            userService.update(user);
            return new Result(true, MessageConstant.UPDATE_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.UPDATE_USER_FAIL);
        }
    }
    //根据id查询
    @GetMapping("findById/{id}")
    public Result findById(@PathVariable("id") Integer id) {

        try {
            User user = userService.findById(id);
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS, user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    /**
     * 新增操作
     * @param user
     * @return
     */
    @PostMapping("/insert")
    public Result insert(@RequestBody User user) {
        try {
            userService.insert(user);
            return new Result(true, MessageConstant.ADD_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_USER_FAIL);
        }
    }

    /**
     * 删除操作
     * @param id
     * @return
     */
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {

        try {
            userService.delete(id);
            return new Result(true, MessageConstant.DELETE_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_USER_FAIL);
        }
    }
}
